package com.zmn.oms.zmn.business.impl.discount;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.zmn.common.constant.FicoConsts;
import com.zmn.common.constant.GlobalConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.math.MathUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.reflect.BeanMapper;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.dms.common.dto.coup.dio.coupon.CoupLockDIO;
import com.zmn.dms.common.dto.coup.dro.coupon.CoupLockDRO;
import com.zmn.dms.common.enums.DiscountTypeEnums;
import com.zmn.dms.common.enums.coup.ThirdPlatEnum;
import com.zmn.dms.dubbo.interfaces.coup.coupon.CoupModifyRemoteService;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.common.constant.ChannelConsts;
import com.zmn.oms.common.constant.DiscountConsts;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.QueueOrderNodeNotifyDTO;
import com.zmn.oms.model.bo.orderamount.CalcAddOrderAmountDIO;
import com.zmn.oms.model.bo.orderamount.DiscountConditionParamsDIO;
import com.zmn.oms.model.bo.orderamount.OrderAmountCalcBO;
import com.zmn.oms.model.bo.orderamount.OrderAmountDIO;
import com.zmn.oms.model.dto.order.proxy.CreateOrderDTO;
import com.zmn.oms.model.dto.order.proxy.OrderDiscountDTO;
import com.zmn.oms.model.dto.product.OrderProductDTO;
import com.zmn.oms.model.entity.discount.OrderDiscount;
import com.zmn.oms.model.entity.order.OrderExtend;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.services.interfaces.discount.OrderDiscountService;
import com.zmn.oms.services.interfaces.order.OrderExtendService;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.daowei.DaoweiConsts;
import com.zmn.oms.zmn.business.interfaces.discount.ChannelDiscountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 类描述：
 *
 * @author LiangHailong
 * @date 2019/11/28 20:13
 */
@Slf4j
@Service
public class ChannelDiscountServiceImpl implements ChannelDiscountService {

    @Autowired
    private OrderWorkService orderWorkService;
    @Autowired
    private OrderExtendService orderExtendService;
    @Autowired
    private OrderDiscountService orderDiscountService;

    @Autowired
    private RedisManager redisManager;

    // 头条，百度，搜狗系列渠道临时优惠来源ID
    private static final int TBS_TEMP_DISCOUNT_SOURCE_ID = 1622538000;

    @DubboReference(version = com.zmn.dms.dubbo.constant.DmsDubboConsts.INTERFACE_VERSION, check = false)
    private CoupModifyRemoteService coupModifyRemoteService;

    // 渠道-产品优惠映射
    private static Map<String, Map<String, Integer>> CHANNEL_MAP = new HashMap<>();
    // 初始化：渠道-产品优惠映射
    static {
        Map<String, Integer> daoweiDiscountMap = new HashMap<>();
        daoweiDiscountMap.put("10472", 9800);	// 套餐二：油烟机不拆机+燃气灶台面清洗
        daoweiDiscountMap.put("10428", 13800);	// 套餐一：柜机空调清洗+2台挂机空调清洗
        daoweiDiscountMap.put("10731", 7600);	// 冰箱清洗（401L-500L）
        daoweiDiscountMap.put("10010", 4100);	// 挂机空调清洗
        daoweiDiscountMap.put("10011", 4900);	// 方形柜机空调清洗
        daoweiDiscountMap.put("10036", 4800);	// 波轮洗衣机清洗（不拆机）
        daoweiDiscountMap.put("10711", 4900);	// 波轮洗衣机清洗（拆机）
        daoweiDiscountMap.put("10076", 6600);	// 油烟机清洗（不拆机）
        daoweiDiscountMap.put("10285", 9100);	// 油烟机清洗（拆机洗）
        daoweiDiscountMap.put("10001", 1000);	// 定频挂机空调维修（1-1.5P）
        daoweiDiscountMap.put("10021", 1000);	// 冰箱维修（≤200L）
        daoweiDiscountMap.put("10547", 1000);	// 波轮全自动洗衣机维修（5kg及以下）
        daoweiDiscountMap.put("10044", 1000);	// 家用电视机维修（≤32吋）
        daoweiDiscountMap.put("10598", 1000);	// 电热水器维修（<60L）
        daoweiDiscountMap.put("10073", 1000);	// 普通油烟机维修
        daoweiDiscountMap.put("10754", 1000);	// 壁挂炉维修（≤16L）
        daoweiDiscountMap.put("10068", 1000);	// 普通燃气灶维修
        daoweiDiscountMap.put("10122", 1000);	// 电暖炉维修
        daoweiDiscountMap.put("10124", 1000);	// 除湿机维修
        daoweiDiscountMap.put("10101", 1000);	// 微波炉维修
        daoweiDiscountMap.put("10115", 1000);	// 净水器维修
        daoweiDiscountMap.put("10104", 1000);	// 电磁炉维修
        daoweiDiscountMap.put("10098", 1000);	// 电饭煲维修
        daoweiDiscountMap.put("10092", 1000);	// 烤箱维修
        daoweiDiscountMap.put("10105", 1000);	// 消毒柜维修
        daoweiDiscountMap.put("10094", 1000);	// 洗碗机维修
        daoweiDiscountMap.put("10129", 1000);	// 空气净化器维修
        daoweiDiscountMap.put("10111", 1000);	// 咖啡机维修
        daoweiDiscountMap.put("10085", 1000);	// 冰柜维修（＜300L）
        daoweiDiscountMap.put("10083", 1000);	// 制冰机维修
        daoweiDiscountMap.put("10130", 1000);	// 风幕机维修
        daoweiDiscountMap.put("10113", 1000);	// 烘干机维修
        daoweiDiscountMap.put("10120", 1000);	// 甩干机维修
        daoweiDiscountMap.put("10121", 1000);	// 开水机维修
        daoweiDiscountMap.put("10119", 1000);	// 吸尘器维修
        daoweiDiscountMap.put("10135", 1000);	// 按摩椅维修
        daoweiDiscountMap.put("10139", 1000);	// 跑步机维修
        daoweiDiscountMap.put("10148", 1000);	// 110V电压电器维修
        daoweiDiscountMap.put("10153", 1000);	// 马桶疏通
        daoweiDiscountMap.put("10109", 1000);	// 蒸饭车维修
        // 到位APP
        CHANNEL_MAP.put("1210", daoweiDiscountMap);
        // 到位电通王
        CHANNEL_MAP.put("10108", daoweiDiscountMap);
        // 到位快益修
        CHANNEL_MAP.put("33551", daoweiDiscountMap);

        // 58C店
        Map<String, Integer> discountMap_58Client = new HashMap<>();
        discountMap_58Client.put("10834", 2000);  // 挂机空调清洗
        discountMap_58Client.put("10833", 2000);  // 柜机空调清洗
        discountMap_58Client.put("11144", 8900);  // 家用中央空调清洗（仅限5个风口）
        discountMap_58Client.put("10837", 1000);  // 冰箱清洗（单/双开门）
        discountMap_58Client.put("10840", 1000);  // 洗衣机清洗
        discountMap_58Client.put("10841", 3000);  // 电热水器清洗
        discountMap_58Client.put("10846", 4000);  // 油烟机清洗
        discountMap_58Client.put("11085", 7800);  // （1台方形柜机+2台挂机）空调清洗
        discountMap_58Client.put("11087", 4800);  // 2台挂机空调清洗
        discountMap_58Client.put("11084", 4700);  // （1台方形柜机+1台挂机）空调清洗
        discountMap_58Client.put("11086", 9800);  // （1台方形柜机+3台挂机）空调清洗
        discountMap_58Client.put("11088", 1700);  // （单/双门冰箱+油烟机不拆机）清洗
        discountMap_58Client.put("11089", 6000);  // （对开门冰箱+油烟机不拆机）清洗
        discountMap_58Client.put("10844", 2800);  // 套餐一：1台热水器清洗+1台波轮洗衣机清洗（均不拆机清洗）
        discountMap_58Client.put("11092", 3800);  // （油烟机不拆机+微波炉）清洗
        discountMap_58Client.put("11093", 3800);  // （油烟机不拆机+燃气灶台面）清洗
        discountMap_58Client.put("11091", 4800);  // （波轮洗衣机+油烟机）不拆机清洗
        discountMap_58Client.put("11145", 14400); // 家电任选四件（不拆机）清洗
        discountMap_58Client.put("11094", 4400);  // （油烟机不拆机+燃气灶台面+单/双门冰箱+微波炉）清洗
        discountMap_58Client.put("10831", 1000);  // 110V电压电器
        discountMap_58Client.put("10801", 1000);  // 吸尘器维修
        discountMap_58Client.put("10977", 1000);  // 其他位置防水
        discountMap_58Client.put("10918", 1000);  // 外墙面防水补漏
        discountMap_58Client.put("10913", 1000);  // 卫生间防水补漏
        discountMap_58Client.put("10922", 1000);  // 纱窗安装、维修
        discountMap_58Client.put("10858", 1000);  // 油烟机拆卸、安装
        discountMap_58Client.put("10826", 1000);  // 音响维修
        discountMap_58Client.put("11096", 1000);  // 新风系统维修
        discountMap_58Client.put("10808", 1000);  // 空调扇维修
        discountMap_58Client.put("10829", 1000);  // 电脑维修
        discountMap_58Client.put("10832", 1000);  // 安防监控
        discountMap_58Client.put("10828", 1000);  // 投影仪维修
        discountMap_58Client.put("10861", 1000);  // 净水器安装
        discountMap_58Client.put("10810", 1000);  // 干手器维修
        discountMap_58Client.put("10791", 1000);  // 粉碎机维修
        discountMap_58Client.put("10827", 1000);  // 打印机维修
        discountMap_58Client.put("10902", 1000);  // 更换把手（普通把手）
        discountMap_58Client.put("10885", 1000);  // 普通五金挂件安装（2个起装）
        discountMap_58Client.put("10883", 1000);  // 晾衣杆维修安装
        discountMap_58Client.put("10882", 1000);  // 多功能浴霸拆卸、安装
        discountMap_58Client.put("10816", 1000);  // 自动售卖机维修
        discountMap_58Client.put("10862", 1000);  // 干手器拆卸、安装
        discountMap_58Client.put("10908", 1000);  // 蹲便疏通
        discountMap_58Client.put("11107", 1000);  // 煮食炉维修
        discountMap_58Client.put("11102", 1000);  // 制冰机维修
        discountMap_58Client.put("11104", 1000);  // 蒸饭车维修
        discountMap_58Client.put("10781", 1000);  // 蒸包机维修
        discountMap_58Client.put("10815", 1000);  // 冷藏展示柜维修
        discountMap_58Client.put("10804", 1000);  // 油汀维修
        discountMap_58Client.put("10799", 1000);  // 甩干机维修
        discountMap_58Client.put("10819", 1000);  // 跑步机维修
        discountMap_58Client.put("11115", 1000);  // 开水机维修
        discountMap_58Client.put("10796", 1000);  // 地暖维修
        discountMap_58Client.put("10797", 1000);  // 干洗机维修
        discountMap_58Client.put("10811", 1000);  // 风幕机维修
        discountMap_58Client.put("10813", 1000);  // 冰柜维修
        discountMap_58Client.put("10820", 1000);  // 按摩椅维修
        discountMap_58Client.put("10776", 1000);  // 电压力锅维修
        discountMap_58Client.put("11108", 1000);  // 烤箱维修
        discountMap_58Client.put("10792", 1000);  // 咖啡机维修
        discountMap_58Client.put("10777", 1000);  // 电饭煲维修
        discountMap_58Client.put("10805", 1000);  // 除湿机维修
        discountMap_58Client.put("10915", 1000);  // 阳台防水补漏
        discountMap_58Client.put("10914", 1000);  // 厨房防水补漏
        discountMap_58Client.put("10887", 1000);  // 卷闸门开锁
        discountMap_58Client.put("10854", 1000);  // 电热水器拆卸、安装
        discountMap_58Client.put("10806", 1000);  // 净水器维修
        discountMap_58Client.put("10803", 1000);  // 电暖炉维修
        discountMap_58Client.put("10780", 1000);  // 洗碗机维修
        discountMap_58Client.put("10795", 1000);  // 空气净化器维修
        discountMap_58Client.put("10923", 1000);  // 沙发翻新、维修
        discountMap_58Client.put("10873", 1000);  // 洗手盆拆卸、安装、维修
        discountMap_58Client.put("10851", 1000);  // 冰箱拆卸、安装
        discountMap_58Client.put("10860", 1000);  // 消毒柜拆卸、安装
        discountMap_58Client.put("10859", 1000);  // 洗碗机拆卸、安装
        discountMap_58Client.put("10911", 1000);  // 浴缸疏通
        discountMap_58Client.put("10904", 1000);  // 更换锁体
        discountMap_58Client.put("10889", 1000);  // 保险柜开锁
        discountMap_58Client.put("10893", 1000);  // 轿车开锁
        discountMap_58Client.put("10865", 1000);  // 水管清洗
        discountMap_58Client.put("10774", 1000);  // 微波炉维修
        discountMap_58Client.put("10788", 1000);  // 电磁炉维修
        discountMap_58Client.put("10773", 1000);  // 油烟机维修
        discountMap_58Client.put("10876", 1000);  // 浴室拆卸、安装、维修
        discountMap_58Client.put("10868", 1000);  // 简易淋浴房拆卸、安装
        discountMap_58Client.put("10899", 1000);  // 普通锁具安装
        discountMap_58Client.put("10886", 1000);  // 普通防盗门开锁
        discountMap_58Client.put("10905", 1000);  // 更换锁芯
        discountMap_58Client.put("10857", 1000);  // 燃气灶拆卸、安装
        discountMap_58Client.put("10856", 1000);  // 太阳能热水器安装
        discountMap_58Client.put("10921", 1000);  // 门窗安装、维修
        discountMap_58Client.put("10864", 1000);  // 普通家用灯具安装、维修
        discountMap_58Client.put("10906", 1000);  // 洗菜盆疏通
        discountMap_58Client.put("10909", 1000);  // 马桶疏通
        discountMap_58Client.put("10907", 1000);  // 洗手盆疏通
        CHANNEL_MAP.put("1322", discountMap_58Client);

        // 58独家
        Map<String, Integer> discountMap_58DuJia = new HashMap<>();
        discountMap_58DuJia.put("10834", 2000);  // 挂机空调清洗
        discountMap_58DuJia.put("10837", 1000);  // 冰箱清洗（单/双开门）
        discountMap_58DuJia.put("10840", 1000);  // 洗衣机清洗
        discountMap_58DuJia.put("10841", 3000);  // 电热水器清洗
        discountMap_58DuJia.put("10846", 4000);  // 油烟机清洗
        discountMap_58DuJia.put("11085", 7800);  // （1台方形柜机+2台挂机）空调清洗
        discountMap_58DuJia.put("11087", 4800);  // 2台挂机空调清洗
        discountMap_58DuJia.put("11084", 4700);  // （1台方形柜机+1台挂机）空调清洗
        discountMap_58DuJia.put("11086", 9800);  // （1台方形柜机+3台挂机）空调清洗
        discountMap_58DuJia.put("11088", 1700);  // （单/双门冰箱+油烟机不拆机）清洗
        discountMap_58DuJia.put("11089", 6000);  // （对开门冰箱+油烟机不拆机）清洗
        discountMap_58DuJia.put("10844", 2800);  // 套餐一：1台热水器清洗+1台波轮洗衣机清洗（均不拆机清洗）
        discountMap_58DuJia.put("11093", 3800);  // （油烟机不拆机+燃气灶台面）清洗
        discountMap_58DuJia.put("11091", 4800);  // （波轮洗衣机+油烟机）不拆机清洗
        discountMap_58DuJia.put("11145", 14400); // 家电任选四件（不拆机）清洗
        discountMap_58DuJia.put("11094", 4400);  // （油烟机不拆机+燃气灶台面+单/双门冰箱+微波炉）清洗
        discountMap_58DuJia.put("10826", 1000);  // 音响维修
        discountMap_58DuJia.put("10825", 1000);  // 功放维修
        discountMap_58DuJia.put("10797", 1000);  // 干洗机维修
        discountMap_58DuJia.put("10810", 1000);  // 干手器维修
        discountMap_58DuJia.put("10791", 1000);  // 粉碎机维修
        discountMap_58DuJia.put("10815", 1000);  // 冷藏展示柜维修
        discountMap_58DuJia.put("10827", 1000);  // 打印机维修
        discountMap_58DuJia.put("10832", 1000);  // 安防监控
        discountMap_58DuJia.put("10808", 1000);  // 空调扇维修
        discountMap_58DuJia.put("11096", 1000);  // 新风系统维修
        discountMap_58DuJia.put("10831", 1000);  // 110V电压电器
        discountMap_58DuJia.put("10801", 1000);  // 吸尘器维修
        discountMap_58DuJia.put("11107", 1000);  // 煮食炉维修
        discountMap_58DuJia.put("11102", 1000);  // 制冰机维修
        discountMap_58DuJia.put("11104", 1000);  // 蒸饭车维修
        discountMap_58DuJia.put("10781", 1000);  // 蒸包机维修
        discountMap_58DuJia.put("10773", 1000);  // 油烟机维修
        discountMap_58DuJia.put("10804", 1000);  // 油汀维修
        discountMap_58DuJia.put("10775", 1000);  // 饮水机维修
        discountMap_58DuJia.put("10789", 1000);  // 消毒柜维修
        discountMap_58DuJia.put("10780", 1000);  // 洗碗机维修
        discountMap_58DuJia.put("10774", 1000);  // 微波炉维修
        discountMap_58DuJia.put("10799", 1000);  // 甩干机维修
        discountMap_58DuJia.put("10769", 1000);  // 燃气热水器维修
        discountMap_58DuJia.put("10770", 1000);  // 电热水器维修
        discountMap_58DuJia.put("10772", 1000);  // 燃气灶维修
        discountMap_58DuJia.put("10819", 1000);  // 跑步机维修
        discountMap_58DuJia.put("11108", 1000);  // 烤箱维修
        discountMap_58DuJia.put("11115", 1000);  // 开水机维修
        discountMap_58DuJia.put("10792", 1000);  // 咖啡机维修
        discountMap_58DuJia.put("10806", 1000);  // 净水器维修
        discountMap_58DuJia.put("10795", 1000);  // 空气净化器维修
        discountMap_58DuJia.put("10798", 1000);  // 烘干机维修
        discountMap_58DuJia.put("10811", 1000);  // 风幕机维修
        discountMap_58DuJia.put("10776", 1000);  // 电压力锅维修
        discountMap_58DuJia.put("10803", 1000);  // 电暖炉维修
        discountMap_58DuJia.put("10777", 1000);  // 电饭煲维修
        discountMap_58DuJia.put("10788", 1000);  // 电磁炉维修
        discountMap_58DuJia.put("10805", 1000);  // 除湿机维修
        discountMap_58DuJia.put("10813", 1000);  // 冰柜维修
        discountMap_58DuJia.put("10981", 1000);  // 壁挂炉维修
        discountMap_58DuJia.put("10820", 1000);  // 按摩椅维修
        discountMap_58DuJia.put("10763", 1000);  // 挂机空调维修
        discountMap_58DuJia.put("10767", 1000);  // 洗衣机维修
        discountMap_58DuJia.put("10768", 1000);  // 电视维修
        discountMap_58DuJia.put("10766", 1000);  // 冰箱维修
        discountMap_58DuJia.put("11273", 3000);  // 空调加氟
        CHANNEL_MAP.put("1511", discountMap_58DuJia);
    }

    @Override
    public Integer getOrderDiscountAmount(CreateOrderDTO createOrderDTO) {
        int channelID = createOrderDTO.getChannelId();

        List<OrderDiscountDTO> discountList = null;

        if (channelID == OrderConsts.CHANNEL_ID_DJ58_APP    // 58到家APP
                || channelID == OrderConsts.CHANNEL_ID_DJ58_DUJIA   // 58到家独家
                || channelID == OrderConsts.CHANNEL_ID_DJ58_CLIENT  // 58到家C店
                || channelID == OrderConsts.CHANNEL_ID_DIANPING     // 点评到家
                || channelID == OrderConsts.CHANNEL_ID_JD_DAOJIA) {  // 京东到家
            discountList = createOrderDTO.getOrderDiscountList();
        }
        // 到位
        else if (channelID == DaoweiConsts.CHANNEL_ID_APP
                || channelID == DaoweiConsts.CHANNEL_ID_DTW
                || channelID == DaoweiConsts.CHANNEL_ID_KYX) {
            discountList = discountDaowei(createOrderDTO);
        }
        // 临时优惠
        else if (CollectionUtils.isNotEmpty(createOrderDTO.getOrderDiscountList())){

            // 头条，百度，搜狗系列渠道临时优惠
            discountList = createOrderDTO.getOrderDiscountList().stream().filter(
                    discountDTO -> Objects.equals(discountDTO.getSourceId() , TBS_TEMP_DISCOUNT_SOURCE_ID)
            ).collect(Collectors.toList());
        }

        // 计算优惠金额
        if (CollectionUtils.isNotEmpty(discountList)) {
            int sum = discountList.stream()
                    .filter(item -> item.getAmount() != null)
                    .mapToInt(item -> item.getAmount())
                    .sum();
            return sum > 0 ? sum : null;
        }

        return null;
    }

    /**
     * 头条、百度、搜狗系列渠道临时优惠5元
     * @param createOrderDTO
     */
    @Override
    public void tbsTempDiscountFiveYuan(CreateOrderDTO createOrderDTO) {

        if (Objects.isNull(createOrderDTO)) {
            return;
        }

        // 时间控制
        long startTime = 1622476800000L;    // 2020-12-01 00:00:00
//        long endTime = 1672502399000L;      // 2022-12-31 23:59:59
        long endTime = 1662047999000L;      // 2022-09-01 23:59:59
        long currentTime = DateUtil.getNowTimestampMillis();
        if (currentTime < startTime || currentTime > endTime) {
            return;
        }

        OrderDiscountDTO orderDiscountDTO = new OrderDiscountDTO();
        orderDiscountDTO.setAmount(500);
        orderDiscountDTO.setRemark("活动优惠");
        orderDiscountDTO.setSourceId(TBS_TEMP_DISCOUNT_SOURCE_ID);
        orderDiscountDTO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
        orderDiscountDTO.setTypeDesc(OrderConsts.getDiscountTypeName(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE));

        List<OrderDiscountDTO> discountList = new ArrayList<>(1);
        discountList.add(orderDiscountDTO);

        createOrderDTO.setOrderDiscountList(discountList);
    }

    @Override
    public void modifyMeiTuanChannelDiscount(Long orderId, String couponCode) {
        List<OrderDiscount> orderDiscountList = orderDiscountService.listByOrderId(orderId);
        OrderDiscount orderDiscount = orderDiscountList.stream()
                .filter(e -> Objects.equals(e.getThirdCode(), com.zmn.consts.GlobalConsts.NO)
                        && Objects.equals(e.getThirdCoupPlat(), ThirdPlatEnum.THIRD_COUP_TYPE_MT.getKey())
                        && Objects.equals(e.getItemCode(), couponCode))
                .findFirst().orElse(null);
        if (Objects.isNull(orderDiscount)) {
            log.info("[{}]未找到美团优惠", orderId);
            return;
        }

        OrderDiscount updateDiscount = new OrderDiscount();
        updateDiscount.setDiscountId(orderDiscount.getDiscountId());
        updateDiscount.setOrderId(orderDiscount.getOrderId());
        updateDiscount.setWriteOffStatus(DiscountConsts.WRITE_OFF_STATUS_DO);
        updateDiscount.setUpdater("系统");
        orderDiscountService.updateByPrimaryKeySelective(updateDiscount);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addMeiTuanChannelDiscount(QueueOrderNodeNotifyDTO dto) {
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(dto.getOrderId(), dto.getWorkId());
        if (Objects.isNull(orderWork)) {
            orderWork = orderWorkService.findOrderWorkByKeySrcMaster(dto.getOrderId(), dto.getWorkId());
        }

        // 不是新单返回
        if (!Objects.equals(orderWork.getType(), OrderConsts.ORDER_TYPE_NEW)) {
            return;
        }

        OrderExtend orderExtend = orderExtendService.findOrderExtendByOrderId(orderWork.getOrderId());
        if (Objects.isNull(orderExtend)) {
            orderExtend = orderExtendService.findMiniOrderExtendByOrderIdSrcMaster(orderWork.getOrderId());
            if (Objects.isNull(orderExtend) || StringUtil.isBlank(orderExtend.getOuterData())) {
                return;
            }
        }

        JSONObject jsonObject = JSONObject.parseObject(orderExtend.getOuterData());

        CoupLockDIO coupLockDIO = new CoupLockDIO();

        if (Objects.isNull(jsonObject)) {
            return;
        }

        // 如果不是美团优惠直接返回
        String openShopId = jsonObject.getString("open_shop_uuid");
        if (StringUtil.isBlank(openShopId)) {
            return;
        }

        // 美团信息
        coupLockDIO.setOpenShopUuid(openShopId);
        coupLockDIO.setThirdOrderId(jsonObject.getString("channel_order_id"));
        coupLockDIO.setThirdProductId(jsonObject.getLong("channel_product_id"));
        coupLockDIO.setAmount(jsonObject.getInteger("amount"));
        coupLockDIO.setPromoAmount(jsonObject.getInteger("promo_amount"));

        // 订单信息
        coupLockDIO.setOrderId(orderWork.getOrderId());
        coupLockDIO.setOrderTime(orderWork.getCreateTime());
        coupLockDIO.setCityId(orderWork.getCityId());
        coupLockDIO.setChannelId(orderWork.getChannelId());
        coupLockDIO.setProductId(orderWork.getShowProductId());
        coupLockDIO.setUserId(orderWork.getUserId());
        coupLockDIO.setBizType(orderWork.getBizType());
        coupLockDIO.setWarrantyType(com.zmn.consts.GlobalConsts.YES);
        boolean tariff = Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_FAULT)
                || Objects.equals(orderWork.getServItemType(), OrderConsts.SERVICE_ITEM_TYPE_QUOTATION_THREE);
        coupLockDIO.setTariffOnoffType(tariff ? com.zmn.consts.GlobalConsts.NO : com.zmn.consts.GlobalConsts.NONE);
        log.info("[{}]美团预约下单创建优惠入参：【{}】", orderWork.getOrderId(), JSON.toJSONString(coupLockDIO));
        ResponseDTO<CoupLockDRO> responseDTO = coupModifyRemoteService.addMeituanCoup(coupLockDIO);
        log.info("[{}]美团预约下单创建优惠出参：【{}】", orderWork.getOrderId(), JSON.toJSONString(responseDTO));
        if (!responseDTO.isSuccess() || Objects.isNull(responseDTO.getData())) {
            return;
        }

        CoupLockDRO coupLockDRO = responseDTO.getData();

        // 插入优惠
        OrderDiscount orderDiscount = new OrderDiscount();
        orderDiscount.setOrderId(orderWork.getOrderId());
        orderDiscount.setCateg(coupLockDRO.getCoupType());
        orderDiscount.setCategName(DiscountTypeEnums.getSubName(coupLockDRO.getCoupType()));
        orderDiscount.setType(coupLockDRO.getPreferentialType());
        orderDiscount.setAmount(coupLockDRO.getPreferentialValue());
        orderDiscount.setItemId(coupLockDRO.getCouponId());
        orderDiscount.setItemCode(coupLockDRO.getCouponCode());
        orderDiscount.setSellAmount(coupLockDRO.getSalePrice());
        orderDiscount.setThirdCode(com.zmn.consts.GlobalConsts.NO);
        orderDiscount.setThirdCoupPlat(ThirdPlatEnum.THIRD_COUP_TYPE_MT.getKey());
        orderDiscount.setSourceId(coupLockDRO.getBatchId());
        orderDiscount.setWriteOffStatus(DiscountConsts.WRITE_OFF_STATUS_WAIT);
        orderDiscountService.insert(orderDiscount);

        // 更新工单金额
        orderWork.setTotalAmount(MathUtil.sub(orderWork.getTotalAmount(), coupLockDRO.getPreferentialValue()));
        orderWork.setMasterAmount(MathUtil.sub(orderWork.getMasterAmount(), coupLockDRO.getPreferentialValue()));
        Integer discountAmount = Optional.ofNullable(orderWork.getDiscountAmount()).orElse(0) + Optional.ofNullable(coupLockDRO.getPreferentialValue()).orElse(0);
        orderWork.setDiscountAmount(discountAmount);
        orderWork.setUpdater("系统");
        orderWork.setUpdateTime(DateUtil.getNow());
        orderWorkService.updateOrderWorkByKey(orderWork);
    }

    /**
     * 获取到位优惠
     * @param createOrderDTO
     * @return
     */
    private List<OrderDiscountDTO> discountDaowei(CreateOrderDTO createOrderDTO) {
        List<OrderDiscountDTO> discountList = Lists.newArrayList();

        // 到位APP，到位电通王, 到位快益修优惠活动。  lhl - 2020.03.31
        // 活动时间：至2021年12月31日中每周一至周四的12点至14点
        int channelID = createOrderDTO.getChannelId();
        Map<String, Integer> productDiscountMap = CHANNEL_MAP.get(String.valueOf(channelID));
        if (productDiscountMap != null) {
            long startTime = 1606752000000L;    // 2020-12-01 00:00:00
            long endTime = 1672502399000L;      // 2022-12-31 23:59:59
            Date now = new Date();
            long currentTime = now.getTime();
            if (currentTime >= startTime && currentTime <= endTime) {

                // 每周一至周四的12点至14点
                int currHour = DateUtil.getDatePoint(now, DateUtil.UNIT_HOUR);
                int currWeek = getDayOfWeek(now);
                if ((12 >= currHour && currHour > 14) && (1 < currWeek && currWeek < 6)) {
                    OrderProductDTO orderProduct = createOrderDTO.getOrderProductList().get(0);
                    String productId = String.valueOf(orderProduct.getProductId());
                    Integer discountAmount = productDiscountMap.get(productId);
                    if (discountAmount != null && discountAmount > 0) {
                        int number = Optional.ofNullable(orderProduct.getNumber()).orElse(1);

                        OrderDiscountDTO orderDiscountDTO = new OrderDiscountDTO();
                        orderDiscountDTO.setAmount(discountAmount*number);
                        orderDiscountDTO.setRemark("活动优惠");
                        orderDiscountDTO.setSourceId(GlobalConsts.NONE);
                        orderDiscountDTO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
                        orderDiscountDTO.setTypeDesc(OrderConsts.getDiscountTypeName(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE));
                        orderDiscountDTO.setCateg(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL);
                        orderDiscountDTO.setCategName(FicoConsts.getDiscountCategName(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL));
                        discountList.add(orderDiscountDTO);
                    }
                }

            }
        }
        return discountList;
    }

    /**
     * 计算指定日期是一周中的第几天，默认周日为第一天，即周二为第三天，返回值为3
     * @param date
     * @return
     */
    private static int getDayOfWeek(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(date.getTime());
        return calendar.get(Calendar.DAY_OF_WEEK);
    }

    /**
     * 获取58独家优惠
     * @param createOrderDTO
     * @return
     */
    private List<OrderDiscountDTO> discount58DuJia(CreateOrderDTO createOrderDTO) {
        List<OrderDiscountDTO> discountList = Lists.newArrayList();

        // 活动时间：4月1日至4月30日   lhl - 2020.03.31
        // 另外：产品ID：10834，产品名称：挂机空调清洗，每日前100台立减29元（价格为69元）
        long startTime = 1585670400000L;    // 2020-04-01 00:00:00
        long endTime = 1588262399000L;      // 2020-04-30 23:59:59
        Date now = new Date();
        long currentTime = now.getTime();

        if (currentTime >= startTime && currentTime <= endTime) {

            Map<String, Integer> productDiscountMap = CHANNEL_MAP.get("1511");
            OrderProductDTO orderProduct = createOrderDTO.getOrderProductList().get(0);
            String productId = String.valueOf(orderProduct.getProductId());

            Integer discountAmount = productDiscountMap.get(productId);

            if ("10834".equals(productId)) {
                // 产品ID：10834，产品名称：挂机空调清洗，每日前100台立减29元（价格为69元）
                String redisKey = String.format(RedisKeyConsts.DUJIA_DISCOUNT_REDIS_KEY, DateUtil.toString(now, DateUtil.FORMAT_DATE2));
                Long count = redisManager.incr(redisKey);
                if (count <= 100) {
                    discountAmount = 2900;
                }
            }

            if (discountAmount != null && discountAmount > 0) {
                int number = Optional.ofNullable(orderProduct.getNumber()).orElse(1);

                OrderDiscountDTO orderDiscountDTO = new OrderDiscountDTO();
                orderDiscountDTO.setAmount(discountAmount*number);
                orderDiscountDTO.setRemark("活动优惠");
                orderDiscountDTO.setSourceId(GlobalConsts.NONE);
                orderDiscountDTO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
                orderDiscountDTO.setTypeDesc(OrderConsts.getDiscountTypeName(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE));
                orderDiscountDTO.setCateg(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL);
                orderDiscountDTO.setCategName(FicoConsts.getDiscountCategName(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL));
                discountList.add(orderDiscountDTO);
            }
        }

        return discountList;
    }

    /**
     * 获取58C店优惠
     * @param createOrderDTO
     * @return
     */
    private List<OrderDiscountDTO> discount58Client(CreateOrderDTO createOrderDTO) {
        List<OrderDiscountDTO> discountList = Lists.newArrayList();

        // 活动时间：4月1日至4月30日  lhl - 2020.03.31
        long startTime = 1585670400000L;    // 2020-04-01 00:00:00
        long endTime = 1588262399000L;      // 2020-04-30 23:59:59
        long currentTime = System.currentTimeMillis();

        if (currentTime >= startTime && currentTime <= endTime) {

            Map<String, Integer> productDiscountMap = CHANNEL_MAP.get("1322");
            OrderProductDTO orderProduct = createOrderDTO.getOrderProductList().get(0);

            Integer discountAmount = productDiscountMap.get(String.valueOf(orderProduct.getProductId()));
            if (discountAmount != null && discountAmount > 0) {
                int number = Optional.ofNullable(orderProduct.getNumber()).orElse(1);

                OrderDiscountDTO orderDiscountDTO = new OrderDiscountDTO();
                orderDiscountDTO.setAmount(discountAmount*number);
                orderDiscountDTO.setRemark("活动优惠");
                orderDiscountDTO.setSourceId(GlobalConsts.NONE);
                orderDiscountDTO.setType(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE);
                orderDiscountDTO.setTypeDesc(OrderConsts.getDiscountTypeName(OrderConsts.ORDER_DISCOUNT_TYPE_LIMIT_FREE));
                orderDiscountDTO.setCateg(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL);
                orderDiscountDTO.setCategName(FicoConsts.getDiscountCategName(FicoConsts.ORDER_IN_DISCOUNT_CATEG_CHANNEL));
                discountList.add(orderDiscountDTO);
            }
        }

        return discountList;
    }

}
